package com.example.examplespringboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

@RestController("/accessToken")
public class AccessToken {

    static final String URL = "";

    @Autowired
    RestTemplate restTemplate;

    private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5);


    @GetMapping("/lkx")
    public String test() {

        System.out.println("start: " + System.currentTimeMillis());


        // 按固定频率执行一个任务，每2秒执行一次，1秒后执行
        // 任务开始时的2秒后
        scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
            try {

                getAccessToken(restTemplate);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
        }, 1, 120, TimeUnit.SECONDS);

        return "success";


    }

   void getAccessToken(RestTemplate restTemplate) throws JSONException {

        //1、构建body参数
       JSONObject jsonObject = new JSONObject();
       jsonObject.put("appId","wx2bd684b1cb398f2a");
       jsonObject.put("needFlush",true);

       //2、添加请求头
       HttpHeaders headers = new HttpHeaders();
       headers.add("Content-Type","application/json");

       //3、组装请求头和参数
       HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(jsonObject), headers);

       //4、发起post请求
       ResponseEntity<String> stringResponseEntity = null;
       try {
           stringResponseEntity = restTemplate.postForEntity(URL, formEntity, String.class);
           System.out.println("ResponseEntity----"+stringResponseEntity);
       } catch (RestClientException e) {
           e.printStackTrace();
       }


       //6、获取返回体
       String body = stringResponseEntity.getBody();
       SimpleDateFormat format = new SimpleDateFormat();
       String dateStr = format.format(new Date());
       System.out.println("[]-返回结果："+ dateStr +body);
    }



}
